<template>
  <transition name="fade">
    <div v-if="visible" :class="'toast toast--' + state">
      {{ message }}
    </div>
  </transition>
</template>

<script>
export default {
  name: 'MMessage',
  props: {
    message: {
      type: String,
      required: true,
    },
    state: {
      type: String,
      required: "success",
    },
    duration: {
      type: Number,
      default: 3000,
    },
  },
  data() {
    return {
      visible: true,
      timer: null,
    };
  },
  mounted() {
    this.timer = setTimeout(() => {
      this.visible = false;
    }, this.duration);
  },
  beforeUnmount() {
    clearTimeout(this.timer);
  },
};
</script>

<style scoped>
.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #ddd;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  color: #333;
  white-space: nowrap;
  transition: opacity 0.3s;
  opacity: 1;
  z-index: 1000;
}

.toast--success {
  background-color: #dff0d8;
  border-color: #d6e9c6;
  color: #3c763d;
}

.toast--warning {
  background-color: #fcf8e3;
  border-color: #faebcc;
  color: #8a6d3b;
}

.toast--error {
  background-color: #f2dede;
  border-color: #ebcccc;
  color: #a94442;
}

/* 你可以根据需要添加更多的类型样式 */

/* 隐藏动画 */
.toast[style*="opacity: 0;"] {
  visibility: hidden;
}
</style>